﻿/*
 * Project: IV:MP GUI Editor (http://code.google.com/p/ivmp-gui-editor)
 * Code license: GNU Lesser GPL (http://www.gnu.org/copyleft/lesser.html)
 * 
 * Authors: CrackHD
 * Description: Used to check for updates
 */

using SmartIni;
using System;
using System.Net;
using System.Text;

namespace IvmpEditor
{
    public static class WebUpdates
    {
        /// <summary>
        /// Possible update modes (like automatic or manual)
        /// </summary>
        public enum UpdateModes
        {
            Unknown,

            /// <summary>
            /// Open link in browser, and exit editor
            /// </summary>
            BrowserDownload
        }

        public struct VersionInfo
        {
            public Version LatestVersion;
            public string DownloadLink;
            public string ChangesText;
            public UpdateModes UpdateMode;

            public bool IsUpdateAvailable { get { return LatestVersion > Common.AppVersion; } }
            
            public VersionInfo(IniFile ini)
            {
                LatestVersion = new Version(ini.DefaultNode["LatestVersion"]);
                UpdateMode = (UpdateModes)Enum.Parse(typeof(UpdateModes), ini.DefaultNode["UpdateMode"]);
                DownloadLink = ini.DefaultNode["DownloadLink"];

                ChangesText = string.Empty;
                foreach (var ln in ini["ChangesText"].GetKeys(true))
                    ChangesText += ln + Environment.NewLine;
            }
        }

        const string CheckForUpdatesUrl = "http://dl.dropboxusercontent.com/u/28171641/ivmp-gui-editor/checkforupdates.txt";

        public static VersionInfo GrabUpdatesInfo()
        {
            IniFile ini = null;
            using (var web = new WebClient())
            {
                // Download latest version info, parse
                var versionInfoIni = web.DownloadString(CheckForUpdatesUrl);
                ini = Ini.LoadData(Common.CreateStreamFromString(versionInfoIni, Encoding.UTF8));
            }
            return new VersionInfo(ini);
        }
        public static void DoUpdate(VersionInfo vInf)
        {
            switch (vInf.UpdateMode)
            {
                case UpdateModes.BrowserDownload:
                    if (Common.OpenWebUrl(vInf.DownloadLink, true) == false)
                        throw new ApplicationException("Failed to open download link in web browser.");
                    break;

                default:
                    throw new NotSupportedException("Update mode '" + vInf.UpdateMode + "' is not supported.");
            }
        }
    }
}